package com.bw.redis;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import redis.clients.jedis.Jedis;

public class RedisJava04Hash {
	
	public static void add(String key, String field, String value){
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        
        jedis.hset(key, field, value);
		
	}
	public static Map<String, String> get(String key){
		Jedis jedis = new Jedis("localhost");
		
		Map<String, String> m = jedis.hgetAll(key);
		
		return m ;
	}

    public static void main(String[] args) {
    	add("goodstype","1","衣服");
    	add("goodstype","2","鞋");
    	add("goodstype","3","手机");
    	
    	Map<String,String> m = get("goodstype");
    	for(Entry<String, String> en : m.entrySet()){
    		System.out.println(en.getKey()+":"+en.getValue());
    	}
    	
    	
    }
    
    public static void hashTest02(){

        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //存储数据到Hash中
        jedis.hset("cart_user01", "耐克", "2");
        //存储数据到Hash中
        jedis.hset("cart_user01", "李宁", "5");
        
        Map<String, String> catMap = jedis.hgetAll("cart_user01");  
          
        System.out.println("----------取出信息---------");  
        for(Entry<String, String> entry: catMap.entrySet()){  
              
            System.out.println(entry.getKey() +":" +entry.getValue());  
        }
    }
    /**
     * 直接插入Map
     */
    public static void hashTest01(){
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //存储数据到Hash中
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("id", "1");
        hashMap.put("name", "耐克");
        jedis.hmset("hash_test", hashMap);
        Map<String, String> hashMap2 = new HashMap<String, String>();
        hashMap2.put("id", "2");
        hashMap2.put("name", "李宁");
        jedis.hmset("hash_test", hashMap2);
        
        // 获取存储的数据并输出
        Map<String, String> hm = jedis.hgetAll("hash_test");
        for(Map.Entry<String, String> entry : hm.entrySet() ) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }

//      jedis.hdel("hash_test", "id", "name");
    }
}
